import request, {simplePost} from "@/utils/request";
import {ElMessageBox, ElLoading, FormInstance} from 'element-plus'
import List from "@/model/list";
import {msgError, msgSuccess} from "@/utils/alert";

export default class Edit {

    show: boolean;

    loading: boolean;

    info: any;

    constructor({show = false, loading = false, info = {}}: { show?: boolean, loading?: boolean, info?: any }) {
        this.show = show
        this.loading = loading
        this.info = info
    }

    async init(callback: Function){
        this.loading = true
        await callback(this)
        this.loading = false
    }

    submit({
               formRef,
               url,
               list,
               success,
           }: { formRef?: FormInstance, url: string, list?: List, success?: Function }) {
        if (!formRef) {
            msgError("无法获取表单对象")
            return
        }
        formRef.validate(async (valid, fields) => {
            if (valid) {
                this.loading = true
                try {
                    let res = await simplePost(url, this.info)
                    msgSuccess("保存成功")
                    if (list) {
                        // 刷新列表
                        list.reload()
                    }
                    // 关闭弹窗
                    this.show = false
                    this.loading = false
                    if (success) {
                        success(this)
                    }

                } catch (err) {
                    // 停止加载
                    this.loading = false
                }

            } else {
                for (let prop in fields) {
                    formRef.scrollToField(prop)
                    break
                }
            }
        }).then(r => {
        })
    }

}
